<template>
  <div v-show="visible">
    <div class="grid_cont">
      <div style="display: flex">
        <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
        <div style="margin-left: 10px; font-size: 16px; line-height: 16px">{{
          formParams.title2
        }}</div>
      </div>
      <div style="
          width: 100%;
          height: 1px;
          background-color: rgba(245, 245, 245, 1);
          margin-top: 16px;
          margin-bottom: 10px;
        ">
      </div>
      <div style="background: #fff; padding: 16px 16px 0 16px">
        <div style="display: flex; margin-bottom: 20px">
          <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
          <div style="margin-left: 10px; font-size: 15px; line-height: 16px">学习内容</div>
        </div>
        <el-form ref="formRef" :rules="rules" :model="formParams" style="margin-left: 14px" label-width="140px">
          <el-form-item required label="选择分类：" prop="type">
            <el-select v-model="formParams.type" placeholder="" placement="bottom" style="width: 320px"
              @change="handleChange">
              <el-option v-for="item in optiontype" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item required label="标题：" prop="title">
            <el-input v-model="formParams.title" style="max-width: 320px" placeholder=" " />
          </el-form-item>
          <el-form-item required label="内容：" prop="content">
            <div style="max-width: 586px; text-align: left">
              <div class="introducestyle">
                <Editor v-model="formParams.content" style="max-width: 586px" />
              </div>
            </div>
          </el-form-item>
          <el-form-item required label="封面图片：" prop="coverImage">
            <UploadImg v-model="formParams.coverImage" :limit="1" />
          </el-form-item>
          <el-form-item required label="是否需要答题：" prop="isQuizRequired" @change="isQuizRequiredChange">
            <el-radio-group v-model="formParams.isQuizRequired"
              :disabled="formParams.title2 === '编辑学习图文' ? true : false">
              <el-radio label="true">是</el-radio>
              <el-radio label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div style="background: #fff; padding: 0 16px">
        <div style="display: flex; margin-bottom: 20px">
          <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
          <div style="margin-left: 10px; font-size: 15px; line-height: 16px">学习对象</div>
        </div>
        <el-form ref="formRef2" :rules="rules" :model="formParams" style="margin-left: 14px" label-width="140px">
          <el-form-item required label="参与人员：" prop="user">
            <el-radio-group v-model="formParams.user" :disabled="formParams.title2 === '编辑学习图文' ? true : false">
              <el-radio label="1" @click="getPartyData">全体人员</el-radio>
              <el-radio label="2">指定对象</el-radio>
            </el-radio-group>
            <el-button link type="primary" :disabled="formParams.title2 === '编辑学习图文' ? true : false"
              v-if="formParams.user === '2'" @click="setbtn" style="
                margin-left: 26px;
                width: 80px;
                height: 30px;
                background-color: #ff9900;
                border: 1px solid #ff9900;
                color: rgba(255, 255, 255, 1);
              " class="btnhover">
              设置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="background: #fff; padding: 0 16px" v-if="formParams.isQuizRequired === 'true'">
        <div style="display: flex; margin-bottom: 20px; align-items: center">
          <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
          <div style="margin-left: 10px; font-size: 15px; line-height: 16px">题目设置</div>
          <el-button link type="primary" :disabled="formParams.title2 === '编辑学习图文' ? true : false" @click="alldelbtn"
            class="btnhover" style="
              width: 90px;
              height: 30px;
              background-color: rgba(218, 111, 40, 1);
              margin-left: 12px;
              color: rgba(255, 255, 255, 1);
            ">批量删除</el-button>
          <el-button link type="primary" @click="addqusbtn" :disabled="formParams.title2 === '编辑学习图文' ? true : false"
            class="btnhover" style="
              width: 90px;
              height: 30px;
              background-color: #0a7cc9;
              color: rgba(255, 255, 255, 1);
            ">加一个题目</el-button>
        </div>
        <el-form ref="formRef3" @submit.prevent="handleChange2" :rules="rules" :model="formParams" style="margin-left: 14px" label-width="140px">
          <el-form-item required label="答对几道题通过：" prop="number">
            <el-input v-model="formParams.number" :disabled="formParams.title2 === '编辑学习图文' ? true : false"
              style="max-width: 94px" @change="handleChange2" placeholder="请输入数量" />
            <span style="color: var(--el-text-color-regular); margin-left: 14px">道题</span>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 题目列表 -->
    <div class="themedata" v-if="formParams.isQuizRequired === 'true'">
      <el-checkbox-group v-model="checkedtheme" @change="CheckedthemeChange">
        <div class="theme-item" v-for="(item, index) in themeList" :key="index">
          <el-checkbox :label="index" />
          <div class="theme-content">
            <el-form ref="formRef4" :rules="themerules" :disabled="formParams.title2 === '编辑学习图文' ? true : false"
              :model="item">
              <el-form-item required label="题目:" prop="questionText">
                <el-input v-model="item.questionText" placeholder="请输入" type="textarea" :rows="7" />
              </el-form-item>
              <el-form-item required label="选项:" prop="theme">
                <el-form-item required label="A" prop="optionA" style="margin-bottom: 18px; width: 100%">
                  <el-input v-model="item.optionA" type="textarea" :rows="1" placeholder="请输入" />
                </el-form-item>
                <el-form-item required label="B" prop="optionB" style="margin-bottom: 18px; width: 100%">
                  <el-input v-model="item.optionB" type="textarea" :rows="1" placeholder="请输入" />
                </el-form-item>
                <el-form-item required label="C" prop="optionC" style="margin-bottom: 18px; width: 100%">
                  <el-input v-model="item.optionC" type="textarea" :rows="1" placeholder="请输入" />
                </el-form-item>
                <el-form-item required label="D" prop="optionD" style="width: 100%">
                  <el-input v-model="item.optionD" type="textarea" :rows="1" placeholder="请输入" />
                </el-form-item>
              </el-form-item>
              <el-form-item required label="答案" prop="correctAnswers">
                <el-checkbox-group v-model="item.correctAnswers">
                  <el-checkbox value="A" label="A" />
                  <el-checkbox value="B" label="B" />
                  <el-checkbox value="C" label="C" />
                  <el-checkbox value="D" label="D" />
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-checkbox-group>
    </div>
    <div class="grid_cont2">
      <el-button class="grid_btn" @click="gridCancel" style="
          background-color: rgba(255, 255, 255, 1);
          border: 1px solid rgba(187, 187, 187, 1);
          color: rgba(142, 142, 142, 1);
        ">取消</el-button>
      <el-button class="grid_btn" @click="gridSure"
        style="background-color: #ff9900; border: 1px solid #ff9900; color: #fff">确定</el-button>
    </div>
    <SelectDialog v-model:visible="selectDialogVisible" :userData="userData" @getuserData="getuserData" />
  </div>
</template>

<script lang="ts" setup>
import * as getlearnApi from '@/api/spb/partyMemberLearning/index'
import SelectDialog from './selectDialog.vue'
import { cloneDeep } from 'lodash-es'
const selectDialogVisible = ref(false)
const formParams = reactive({
  type: '',
  title: '',
  content: '',
  coverImage: '',
  isQuizRequired: 'true',
  number: 1,
  user: '1',
  userIds: [],
  title2: '',
  materialId: ''//学习材料id
})
const formRef = ref() // 表单 Ref
const formRef2 = ref() // 表单 Ref
const formRef3 = ref() // 表单 Ref
const formRef4 = ref() // 表单 Ref
const checkedtheme = ref([])//选中题目
const CheckedthemeChange = (value: string[]) => {
}
function handleChange(value) {
  themeList.value[0].materialId = formParams.type
  themeList2[0].materialId = formParams.type
}
function handleChange2(value) {
  themeList.value[0].passingScore = formParams.number
}
const themeList = ref([
  {
    materialId: formParams.type, //分类id
    questionText: '', //题目名称
    optionA: '',
    optionB: '',
    optionC: '',
    optionD: '',
    correctAnswers: [] as any,
    passingScore: formParams.number
  }
])
// 题目列表模版
const themeList2 = [
  {
    materialId: formParams.type, //分类id
    questionText: '', //题目名称
    optionA: '',
    optionB: '',
    optionC: '',
    optionD: '',
    correctAnswers: [],
    passingScore: formParams.number
  }
]
const themerules = reactive({
  questionText: [{ required: true, message: '题目名称不能为空！', trigger: 'blur' }],
  optionA: [{ required: true, message: 'A不能为空！', trigger: 'blur' }],
  optionB: [{ required: true, message: 'B不能为空！', trigger: 'blur' }],
  optionC: [{ required: true, message: 'C不能为空！', trigger: 'blur' }],
  optionD: [{ required: true, message: 'D不能为空！', trigger: 'blur' }],
  correctAnswers: [
    {
      type: 'array',
      required: true,
      message: '答案不能为空！',
      trigger: 'change'
    }
  ]
})
const rules = reactive({
  type: [{ required: true, message: '选择分类不能为空！', trigger: 'change' }],
  title: [{ required: true, message: '标题不能为空！', trigger: 'blur' }],
  content: [
    {
      type: 'paragraph',
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('内容不能为空！'))
        } else {
          let str = value
            .replace(/<[^<p>]+>/g, '')
            .replace(/<[</p>$]+>/g, '')
            .replace(/&nbsp;/gi, '')
            .replace(/<[^<br/>]+>/g, '')
            .replace(/\s+/g, '')
          if (str.length === 0) {
            callback(new Error('请填写内容'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  coverImage: [{ required: true, message: '封面图片不能为空！', trigger: 'blur' }],
  number: [
    {
      pattern: /^(10|[0-9])$/,
      message: '输入答对数量应为数字，最多为题目上限10',
      trigger: 'blur'
    },
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('答对数量不能为空！'))
        } else {
          if (value > themeList.value.length) {
            callback(new Error('答对数量不能超过题目数量'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ]
})
const visible = ref(false)
const optiontype = ref([])
const props = defineProps({
  addShow: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object
  }
})
const userData = ref([])
//指定学习对象
const getuserData = (val) => {
  formParams.userIds = []
  val = val.filter(item => new Set(userList).has(item));
  formParams.userIds = val
}
const emit = defineEmits(['getaddShow', 'geteditData'])
watch(
  () => props.addShow,
  (val) => {
    visible.value = val
  },
  { immediate: true }
)
watch(
  () => props.editData,
  async (val) => {
    if (val) {
      formParams.title = val.title
      formParams.content = val.content
      formParams.title2 = val.dialogtitle
      formParams.coverImage = val.coverImage
      formParams.materialId = val.id
      formParams.type = val.type
      if (props.addShow == true) {
        getTypeData()
        getPartyData()
        formRef.value.validate()
      }
      formParams.number = val.passingScore
      if (val.dialogtitle === '编辑学习图文') {
        formParams.isQuizRequired = val.isQuizRequired
        formParams.userIds = val.userIds
        await getlearnApi.getAllStudy().then((res) => {
          if (res.length === val.allUserCount) {
            formParams.user = "1"
          } else {
            formParams.user = "2"
          }
        })
        getQuestionsData()
      }
      if (val.dialogtitle === '新增学习图文') {
        formParams.isQuizRequired = 'true'
        formParams.user = "1"
        themeList.value = cloneDeep(themeList2)
      }
    }
  },
  { immediate: true }
)

// 获取学习分类
const getTypeData = () => {
  optiontype.value = []
  const params = {
    pageNo: 1,
    pageSize: 100
  }
  getlearnApi.getTypePage(params).then((res) => {
    res.list.forEach((item) => {
      optiontype.value.push({
        label: item.name,
        value: item.id
      })
    })
  })
}
let userList = reactive([])
// 获取全部党员
const getPartyData = () => {
  userList = []
  formParams.userIds = []
  getlearnApi.getAllStudy().then((res) => {
    res.forEach((item) => {
      userList.push(item.id)
      formParams.userIds = userList
    })
  })
}

/** 设置 */
const setbtn = () => {
  selectDialogVisible.value = true
  userData.value = []
}

//是否答题变化
const isQuizRequiredChange = () => {
  if (formParams.isQuizRequired === 'false') {
    formParams.number = 0
  }
}

/** 取消按钮操作 */
const gridCancel = () => {
  checkedtheme.value = []
  visible.value = false
  emit('getaddShow', visible.value)
  emit('geteditData', props.editData.pageNo)
}
/** 确定按钮操作 */
const gridSure = async () => {
  // 校验表单
  await formRef.value.validate()
  await formRef2.value.validate()
  if (formParams.isQuizRequired === 'true') {
    await formRef3.value.validate()
    if (!themeList.value[0].optionA || !themeList.value[0].optionB || !themeList.value[0].optionC || !themeList.value[0].optionD || !themeList.value[0].questionText || themeList.value[0].correctAnswers.length === 0) {
      ElMessage.warning('问题设置为必填项不能为空！')
      return
    }
  }
  // await formRef4.value.validate()
  const LearningData = {
    title: formParams.title,
    content: formParams.content,
    type: formParams.type,
    coverImage: formParams.coverImage,
    isQuizRequired: JSON.parse(formParams.isQuizRequired),
    userIds: formParams.userIds,
    learningQuestionsList: cloneDeep(themeList.value),
    passingScore: formParams.number
  }
  LearningData.learningQuestionsList.forEach((item) => {
    item.correctAnswers = item.correctAnswers.join(',')
  })
  if (formParams.title2 === '新增学习图文') {
    ElMessageBox.confirm('是否确认新增学习图文?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        if (formParams.isQuizRequired === 'false') {
          LearningData.learningQuestionsList = []
        }
        getlearnApi.createStudymaterials(LearningData).then((res) => {
          if (res) {
            ElMessage.success('新增成功！')
            themeList.value = []
            emit('geteditData', props.editData.pageNo)
            visible.value = false
            emit('getaddShow', visible.value)
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消新增学习图文')
      })
  }
  if (formParams.title2 === '编辑学习图文') {
    ElMessageBox.confirm(
      '是否确认编辑学习图文?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const LearnData = {
        title: formParams.title,
        content: formParams.content,
        type: formParams.type,
        coverImage: formParams.coverImage,
        id: props.editData.id
      }
      getlearnApi.updateStudymaterials(LearnData).then((res) => {
        if (res) {
          ElMessage.success('修改成功！')
          emit('geteditData', props.editData.pageNo)
          visible.value = false
          emit('getaddShow', visible.value)
        }
      })
    })
      .catch(() => {
        ElMessage.info('已取消编辑学习图文')
      })
  }
}

/** 批量删除 */
const alldelbtn = () => {
  if (checkedtheme.value.length === 0) {
    ElMessage.warning('至少选中一条数据！')
    return
  }
  if (themeList.value.length === 1 || checkedtheme.value.length === themeList.value.length) {
    ElMessage.warning('不允许删除，题目数量不能为空！')
    return
  }
  ElMessageBox.confirm('此操作将永久删除选中题目, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (formParams.title2 === '新增学习图文') {
        checkedtheme.value.forEach((item) => {
          themeList.value.forEach((item2, index) => {
            if (item == index) {
              themeList.value.splice(index, 1)
            }
          })
        })
        checkedtheme.value = []
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 增加题目
const addqusbtn = () => {
  if (formParams.title2 === '编辑学习图文') {
    ElMessage.warning('编辑学习图文不允许增加题目！')
    return
  }
  if (themeList.value.length >= 10) {
    ElMessage.warning('最多10道题,已上限，不允许增加题目！')
    return
  }
  let firstobj = JSON.parse(JSON.stringify(themeList.value[0]))
  for (let key in firstobj) {
    if (Array.isArray(firstobj[key])) {
      firstobj[key] = []
    } else if (typeof firstobj[key] == 'string') {
      firstobj[key] = ''
    } else if (typeof firstobj[key] == 'object') {
      for (let keys in firstobj[key]) {
        firstobj[key][keys] = ''
      }
    }
  }
  themeList.value.push(firstobj)
}
const QuestionList = ref([])
// 获取学习问题
const getQuestionsData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    materialId: formParams.materialId
  }
  getlearnApi.getQuestionsPage(params).then((res) => {
    QuestionList.value = JSON.parse(JSON.stringify(res.list))
    if (res.list.length === 0) {
      themeList.value = themeList2
    } else {
      themeList.value = JSON.parse(JSON.stringify(res.list))
      themeList.value.forEach((item) => {
        item.correctAnswers = item.correctAnswers.slice(1, -1).split(',').map(item => item.trim())
      })
    }
  })
}

onMounted(() => {
})
</script>
<style scoped>
.grid_cont {
  min-height: 600px;
  background: #fff;
}

.grid_cont2 {
  width: 100%;
  background: #fff;
  height: 65px;
  justify-content: center;
  align-items: center;
  display: flex;
  padding: 0;
  box-shadow: 0px -2px 6px 0px rgba(188, 188, 188, 0.65);
}

.grid_btn {
  width: 80px;
  height: 30px;
}

.grid_btn:hover {
  opacity: 0.8;
}

.introducestyle {
  box-shadow: 0 0 0 1px var(--el-disabled-border-color);
  border-radius: 4px;
  background: transparent !important;
}

.introducestyle:hover {
  box-shadow: 0 0 0 1px #ccc !important;
}

.introducestyle::selection {
  box-shadow: 0 0 0 1px #cc352f !important;
}

::v-deep .w-e-text-placeholder {
  top: 10px;
  text-align: justify;
  width: 96%;
}

::v-deep .w-e-bar {
  box-shadow: 0px 1px 0px 0px var(--el-disabled-border-color);
}

::v-deep .w-e-bar:hover {
  box-shadow: 0 1px 0 0 #ccc !important;
}

::v-deep .border-solid {
  border-color: #fff;
  border-radius: 4px;
}

::v-deep .upload .el-upload .el-upload-dragger {
  border: 1px solid var(--el-border-color-darker) !important;
}

::v-deep .upload .el-upload .el-upload-dragger:hover {
  border: 1.5px solid #ccc !important;
}

.btnhover:hover {
  opacity: 0.8;
}

.themedata {
  margin-bottom: 20px;
  padding: 0 30px;
}

.theme-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.theme-item:last-child {
  margin-bottom: 0;
}

::v-deep .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #ccc!important;
}

::v-deep .el-select__wrapper.is-focused {
  box-shadow: 0 0 0 1px #ccc!important;
}

::v-deep .el-textarea__inner:focus {
  box-shadow: 0 0 0 1px #ccc!important;
}

.theme-content {
  width: calc(100% - 30px);
  border: 1px dashed #868686;
  background: #e4e4e4;
  padding: 20px;
  box-sizing: border-box;
}

.theme-item ::v-deep .el-checkbox__label {
  display: none;
}

.theme-content ::v-deep .el-checkbox__label {
  display: block;
}

::v-deep .el-textarea__inner {
  resize: none!important;
}
</style>